package com.ringtheweb.web.lifecycle;

import java.util.Calendar;
import java.util.concurrent.TimeUnit;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Observer;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;

import com.ringtheweb.model.Role;
import com.ringtheweb.model.RoleType;
import com.ringtheweb.model.User;
import com.ringtheweb.persistence.dao.IRoleDAO;
import com.ringtheweb.service.IUserManager;
import com.ringtheweb.service.exception.NonUniqueLoginException;
import com.ringtheweb.service.exception.RoleNotFoundException;
import com.ringtheweb.web.action.MailNotificationAction;

@Name("sipphonyLifeCycle")
@Scope(ScopeType.APPLICATION)
public class SipphonyLifeCycle {
	
	@Logger Log logger;
	
	@In("#{roleDAO}") IRoleDAO roleDAO; 
	
	@In("#{userManager}") IUserManager userManager;
	
	@In(create=true,value="mailNotificationAction") MailNotificationAction mailNotificationAction;
	
	@Observer("org.jboss.seam.postInitialization")	
	public void start() {
		createDefaultRoles();
		sendRegistrationApprovalNotifications();
	}
	

	public void createDefaultRoles() {

		for (RoleType roleName : RoleType.values()) {
			Role role = roleDAO.findByName(roleName.name());
			if (null == role) {
				role = new Role(roleName.name(),"Role "+roleName.name());
				roleDAO.makePersistent(role);
			}
		}
		
		User user = new User();
		user.setLoginName("admin");
		user.setPassword("admin");
		user.setEmail("root@localhost");
		try {
			userManager.saveUserInRole(user, RoleType.ADMIN);
		}
		catch(NonUniqueLoginException e) {
			e.printStackTrace();
		}
		catch (RoleNotFoundException e) {
			e.printStackTrace();
		}
		
	}
	
	public void sendRegistrationApprovalNotifications() {
		Calendar endDate = Calendar.getInstance();
		endDate.add(Calendar.YEAR,1);
		mailNotificationAction.scheduleSendApprovalMailsForUser(Calendar.getInstance().getTime(),
				TimeUnit.SECONDS.toMillis(30), endDate.getTime());
	}

}
